﻿using System.Linq;

namespace Nxg.Blog.Core.Commands.Posts {
    public class DeletePostCommand {
        public int PostId { get; set; }
    }

    public class DeletePostCommandInvoker : ICommandInvoker<DeletePostCommand, CommandResult> {
        private readonly DataContext _db;

        public DeletePostCommandInvoker (DataContext db) {
            _db = db;
        }

        public CommandResult Execute (DeletePostCommand command) {
            var comments = _db.Comment.Where (x => x.PostId == command.PostId);
            if (comments.Count () > 0) {
                _db.Comment.RemoveRange (comments);
            }
            var post = _db.Post.Single (x => x.Id == command.PostId);
            _db.Post.Remove (post);
            _db.SaveChanges ();
            return CommandResult.SuccessResult;
        }
    }
}